package net.ifilm.controller;

import net.ifilm.common.Constants;
import net.ifilm.common.cache.ICache;
import net.ifilm.common.cache.ICacheManager;
import net.ifilm.entity.FilmType;
import net.ifilm.entity.Region;
import net.ifilm.entity.SystemParam;
import net.ifilm.service.CacheUpdService;
import net.ifilm.service.FilmService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bg/system")
public class SystemController {

    private static Log log = LogFactory.getLog(SystemController.class);

    @Autowired
    private CacheUpdService cacheUpdService;

    @Autowired
    private ICache<Object, Object> defaultCache;

    @Autowired
    private FilmService filmService;

    @RequestMapping(value="/cacheUpdate", method=RequestMethod.GET)
    public String cacheUpdate(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        resonse.setCharacterEncoding("utf-8");
        resonse.setContentType("text/html;charset=utf-8");
        PrintWriter out = resonse.getWriter();

        String result = null;
        try {
            int cacheType = Integer.parseInt(request.getParameter("cacheType"));
            if (log.isInfoEnabled()) {
                log.info("update cache for cacheType " + cacheType + " is beginning.");
            }

            switch (cacheType) {
                case 1:
                    cacheUpdService.updAll();
                    break;
                case 2:
                    cacheUpdService.updSlideFilmList();
                    break;
                case 3:
                    cacheUpdService.updSysParamList();
                    break;
                default:
                    break;
            }

            result = "更新完成！";
            if (log.isInfoEnabled()) {
                log.info("update cache for cacheType " + cacheType + " was complated..");
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("update cache failure, " + e.toString());
            }

            result = "缓存更新失败！";
        }

        out.println(result);
        out.close();

        return null;
    }

    @RequestMapping(value="/loadSystemParam", method=RequestMethod.GET)
    public String loadSystemParam(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        resonse.setCharacterEncoding("utf-8");
        resonse.setContentType("text/html;charset=utf-8");
        PrintWriter out = resonse.getWriter();
        StringBuffer returnXML = new StringBuffer();

        ICache cache = cacheUpdService.getDefaultCache();
        List<SystemParam> paramList = (List<SystemParam>) cache.get(Constants.CACHE_KEY_SYSPARAM);
        returnXML.append("<ROOT>");

        String key = request.getParameter("key");
        if (key == null || "".equals(key) || "null".equals(key)) {
            log.info("the key is null and load all systemparam list");

            for (SystemParam systemParam : paramList) {
                returnXML.append("<param name=\"").append(systemParam.getParamName())
                .append("\" ").append("value=\"").append(systemParam.getParamValue())
                .append("\" ").append("status=\"").append(systemParam.getActiveFlag())
                .append("\" ").append("detail=\"").append(systemParam.getDetail())
                .append("\" ").append("id=\"").append(systemParam.getId())
                .append("\"/>");
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info("load systemparam list for key is " + key);
            }

            String paramName = null;
            for (SystemParam systemParam : paramList) {
                paramName = systemParam.getParamName();
                if (paramName.indexOf(key) == -1) continue;

                returnXML.append("<param name=\"").append(systemParam.getParamName())
                        .append("\" ").append("value=\"").append(systemParam.getParamValue())
                        .append("\" ").append("status=\"").append(systemParam.getActiveFlag())
                        .append("\" ").append("detail=\"").append(systemParam.getDetail())
                        .append("\" ").append("id=\"").append(systemParam.getId())
                        .append("\"/>");
            }
        }
        returnXML.append("</ROOT>");

        out.println(returnXML.toString());
        out.close();
        return null;
    }

    @RequestMapping(value="/loadControlParam")
    public String loadControlParam(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        request.setAttribute("switch", Constants.switchSex);
        request.setAttribute("logLevel", Constants.logLevel);
        request.setAttribute("performance", Constants.performance);
        return "/bg/system/control.jsp";
    }

    @RequestMapping(value="/loadSysParam")
    public String loadSysParam(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        Map<String, SystemParam> systemParamMap = (Map<String, SystemParam>)defaultCache.get(Constants.CACHE_KEY_SYSPARAM);
        request.setAttribute("systemParamMap", systemParamMap);
        return "/bg/system/systemParam.jsp";
    }

    @RequestMapping(value="/updateSystemParam")
    public String updateSystemParam(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        String value = request.getParameter("value");
        String key = request.getParameter("key");
        int id = Integer.parseInt(request.getParameter("id"));

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("id", id);
        parameter.put("paramvalue", value);
        filmService.updateSystemParam(parameter);

        Map<String, SystemParam> systemParamMap = (Map<String, SystemParam>)defaultCache.get(Constants.CACHE_KEY_SYSPARAM);
        SystemParam systemParam = systemParamMap.get(key);
        systemParam.setParamValue(value);

        if (log.isInfoEnabled()) {
            log.info("system parameter id " + id + " is updated");
        }

        return null;
    }

    @RequestMapping(value="/changeSexStatus")
    public String changeSexStatus(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        String sexValue = request.getParameter("sexValue");
        int value = Integer.parseInt(sexValue);
        if (value == 0) {
            Constants.switchSex = true;

            log.info("the sex switch is open");
        } else {
            Constants.switchSex = false;

            log.info("the sex switch is close");
        }

        return null;
    }

    @RequestMapping(value="/changePerformanceStatus")
    public String changePerformanceStatus(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        String sexValue = request.getParameter("performanceValue");
        int value = Integer.parseInt(sexValue);
        if (value == 0) {
            Constants.performance = true;
            log.info("the performance switch is open");
        } else {
            Constants.performance = false;
            log.info("the performance switch is close");
        }

        return null;
    }

    @RequestMapping(value="/changelogStatus")
    public String changelogStatus(ModelMap map, HttpServletRequest request, HttpServletResponse resonse) throws IOException {
        String logValue = request.getParameter("logValue");
        int value = Integer.parseInt(logValue);

        String logFileName = null;
        switch (value) {
            case 1:
                logFileName = "log4j-debug.properties";
                break;
            case 2:
                logFileName = "log4j-info.properties";
                break;
            case 3:
                logFileName = "log4j-warn.properties";
                break;
            case 4:
                logFileName = "log4j-error.properties";
                break;
            default:
                throw new RuntimeException("loglevel value is error");
        }

        Constants.logLevel = value;
        StringBuffer logFilePath = new StringBuffer(request.getRealPath("/"));
        logFilePath.append("/WEB-INF/log4j/").append(logFileName);
        PropertyConfigurator.configure(logFilePath.toString());

        if (log.isInfoEnabled()) {
            log.info("log level switch " + logFilePath.toString());
        }

        return null;
    }

}

